package reference;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author ZhuQi
 * @ClassName SoftReference
 * @Date 2022/9/23 10:57
 * @Version 1.0
 * @Description 测试软引用
 * 软引用只有在 OOM 时才会将其回收，一般是不会进行回收的
 */
public class SoftReferenceDemo {

    public static void main(String[] args) {
        SoftReference<HashMap<String, Object>> hashMapSoftReference =
                new SoftReference<>(new HashMap<>());
        // 输出:hashMapSoftReference: {}
        System.out.println("hashMapSoftReference: " + hashMapSoftReference.get());
        System.gc();

        try {
            TimeUnit.SECONDS.sleep(2L);
            // 输出:GC after-- hashMapSoftReference: {}
            System.out.println("GC after-- hashMapSoftReference: " + hashMapSoftReference.get());
            byte[] bytes = new byte[1024 * 1024 * 20];
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 输出:bytes after-- hashMapSoftReference: null
            System.out.println("bytes after-- hashMapSoftReference: " + hashMapSoftReference.get());
        }
    }
}
